import { Query } from '@/hook/mapgis-api/Query'
import { createDraw } from '@/hook/ol-api/createDraw'
import { setMark } from '@/hook/ol-api/setMark.js'
import { getCurrentInstance, onMounted, ref, watch } from 'vue'
import { useCommonStore } from '@/stores/common'
import { storeToRefs } from 'pinia'
import imgurl from '@/assets/image/location.png'
import { ElMessage } from 'element-plus'

import {claerMap} from '@/hook/MapClear.js'
const formatterStatus = (data) => {
  data = parseInt(data)
  switch (data) {
    case 0:
      return '待处理'
    case 1:
      return '处理中'
    case 2:
      return '已归档'
  }
}
const formatterLevel = (data) => {
  data = parseInt(data)
  switch (data) {
    case 1:
      return '轻微事故'
    case 2:
      return '一般事故'
    case 3:
      return '重大事故'
    case 4:
      return '特大事故'
  }
}

/**需要传入向父组件触发的事件 */
export const addQueryDraw = () => {
  /* 引入公共状态管理对象 */
  const store = useCommonStore()
  const { queryflag } = storeToRefs(store)
  /* 对话框显示状态 */
  const centerDialogVisible = ref(false)
  /* 监听对话框关闭，恢复事情查询功能 */
  watch(centerDialogVisible, (newVal) => {
    queryflag.value = newVal
  })
  let query_result = ref([])
  /* 当前页码 */
  let currentPage = 1
  /* 每页数据量 */
  let pageSize = 5
  /* 显示数据 * */
  const displayData = ref([])
  /* 热力图数据 */
  const Radiusvalue = ref(3)
  const maxRadius = 50
  const Blurvalue = ref(8)
  const maxBlur = 50

  const { proxy } = getCurrentInstance()
  // console.log('proxy', proxy)
  /* 图层设置 */
  let source = new ol.source.Vector({})
  /* 设置高亮图层 */
  let high_layer = new ol.layer.Vector({
    name: '高亮图层',
    source: new ol.source.Vector({})
  })
  /* 设置热力图层 */
  let heat_layer = new ol.layer.Heatmap({
    name: '热力图',
    source: new ol.source.Vector({}),
    blur: Blurvalue.value,
    radius: Radiusvalue.value,
    weight: (feature) => {
      return (feature.get('values_').事件等级)/4
    },
    visible: false
  })
  /* 设置画笔 */
  let draw = createDraw({
    type: 'rectangle',
    source,
    success: handleSuccess
  })
  let $map = proxy.$map

  /* 查询成功回调 */
  function handleSuccess(feature) {
    let geometry = feature.getGeometry()
    let service = {
      name: import.meta.env.VITE_DOC_NAME,
      /* 图层id */
      layerId: 2
    }
    /* 清除高亮数据源 */
    // high_layer.getSource().clear()
    // heat_layer.getSource().clear()
    // source.clear()
    claerMap($map)
    $map.removeInteraction(draw)

    Query.queryByGeom({
      geometry,
      service,
      success: (feature) => {
        // console.log(feature);
        if (!feature) {
          ElMessage({
            message: '未选中要素!',
            type: 'error'
          })
          queryflag.value = false
          // emits('close')
          return
        }
        high_layer.getSource().addFeatures(feature)
        /* 处理热力图数据 */
        heat_layer.getSource().addFeatures(feature)
        /* 清空上一次查询结果 */
        query_result.value = []
        /* 处理查询结果 */
        feature.forEach((item, index) => {
          // console.log(item)
          query_result.value.push({
            编号: index + 1,
            FID: item.get('ol_uid'),
            事件编号: item.get('values_').事件编号,
            事件类型: item.get('values_').事件类型,
            发生时间: item.get('values_').发生时间,
            发生地点: item.get('values_').发生地点,
            车牌号: item.get('values_').车牌号,
            驾驶员: item.get('values_').驾驶员,
            处理状态: formatterStatus(item.get('values_').处理状态)
            // ...item.get("values_"),
          })
        })
        /* 设置分页显示数据 */
        let start = (currentPage - 1) * pageSize
        let end = start + pageSize
        displayData.value = query_result.value.slice(start, end)
        // console.log(query_result.value);
        /* 打开查询对话框 */
        centerDialogVisible.value = true
      }
    })
  }

  // 更新 radius 和 blur 时的响应函数
  const updateRadius = (value) => {
    Radiusvalue.value = value
    if (heat_layer) {
      heat_layer.setRadius(Radiusvalue.value)
    }
  }

  const updateBlur = (value) => {
    Blurvalue.value = value
    if (heat_layer) {
      heat_layer.setBlur(Blurvalue.value)
    }
  }

  onMounted(() => {
    /* 添加高亮图层 */
    // high_layer.setStyle(setAnimateStyle({ map: $map }))
    high_layer.setStyle(setMark(imgurl))
    /* 添加热力图层 */
    $map.addLayer(heat_layer)
    /* 添加画笔 */
    $map.addLayer(high_layer)
    /* 监听热力图层变化 */
    watch(
      [Radiusvalue, Blurvalue],
      () => {
        if (high_layer) {
          heat_layer.setRadius(Radiusvalue.value)
          heat_layer.setBlur(Blurvalue.value)
        }
      },
      { immediate: true }
    )
  })
  /* 开始查询 */
  const activeDraw = () => {
    $map.addInteraction(draw)
  }
  /* 处理翻页 */
  const handleCurrentChange = (newPage) => {
    console.log(newPage)
    currentPage = newPage
    let start = (currentPage - 1) * pageSize
    let end = start + pageSize
    displayData.value = query_result.value.slice(start, end)
  }
  /* 关闭查询对话框 */
  const handleClose = () => {
    centerDialogVisible.value = false
    // emits('close')
  }
  /**取消查询 */
  const cancelQuery = () => {
    $map.removeInteraction(draw)
    claerMap($map)
    // source.clear()
    // high_layer.getSource().clear()
    // heat_layer.getSource().clear()
    queryflag.value = false
  }
  return {
    query_result,
    centerDialogVisible,
    displayData,
    cancelQuery,
    handleCurrentChange,
    handleClose,
    activeDraw,
    updateRadius,
    updateBlur,
    Radiusvalue,
    maxRadius,
    Blurvalue,
    maxBlur
  }
}
